import React, { FC, useDebugValue, useEffect, useState } from 'react'
import MyHead from '../../components/MyHead'
import { useParams } from "react-router-dom"
import { addLikeToNewApi, getNewDetailApi, getCommentListApi, addLikeToNewCommentApi, addCommentToNewAPI } from '../../api/news';
import { baseURL } from '../../api/request';
import { useCommonFunc } from '../../hooks/useCommon';
import "./index.scss"
import { EditSOutline, MessageOutline, LikeOutline, HeartOutline, SendOutline, DeleteOutline, CloseOutline } from 'antd-mobile-icons';
import { Avatar, Badge,Button,Empty, Popup, TextArea } from 'antd-mobile';
import { ShowMessage, ShowSuccess } from '../../utils/message';
import { useDebounceFn } from "ahooks"

const NewsDetail:FC = () => {
  const [data,setData] = useState<any>(null)
  const [commentList, setCommentList] = useState<any>([])
  const [visible,setVisiBle] = useState<boolean>(false)
  const [content,setContent] = useState<string>('')

  const { dateFormat } = useCommonFunc()
  const userInfo = useCommonFunc()
  const params:any = useParams()

  const getNewDetail = async() => {
    let res:any = await getNewDetailApi(params.id)
    if(res.code == '200'){
      setData(res.data)
    }
  }

  const AddLikeToNew = async() => {
    let res:any = await addLikeToNewApi(data.id)
    if(res.code == "200"){
      ShowMessage("点赞成功")
      data.likeNum+=1
      setData({
        ...data
      })
    }
  }

  const getCommentList = async() => {
    let res:any = await getCommentListApi({
      newsId: params.id
    })
    if(res.code == "200"){
      setCommentList(res.rows.reverse())
    }
  }

  const AddLikeToNewComment = async(item:any,index:number) => {
    let res:any = await addLikeToNewCommentApi(item.id)
    if(res.code == "200"){
      ShowSuccess("评论点赞成功")
      item.likeNum+=1
      commentList.splice(index,1,{...item})
      setCommentList([...commentList])
    }
  }


  const todoAddComment = async() => {
    let res:any = await addCommentToNewAPI({
      newsId:params.id,
      content
    })
    if(res.code == "200"){
      setContent('')
      ShowSuccess('发布成功')
      setVisiBle(false)
      getCommentList()
    }
  }

  // 函数防抖 ahooks
  const AddLikes = useDebounceFn()

  // 函数防抖
  const { run } = useDebounceFn(
    AddLikeToNew,
    {
      wait:500,
    }
  )

  useEffect(()=>{
    getNewDetail()
    getCommentList()
  },[])

  return (
      data && <div style={{paddingBottom:60}}>
          <div>
              <MyHead title={data?.title}/>
              <div style={{padding:15}}>
                <img src={baseURL+data?.cover} alt="" style={{width:"100%"}}/>
                <div className="content" style={{ marginTop: 15, fontSize: 16, width: '100%', overflowX: "hidden" }} dangerouslySetInnerHTML={{__html:data?.content.replace(new RegExp('/prod-api/','gi'),baseURL+'/prod-api/')}}></div>
                <div className='time' style={{marginTop:15}}>
                  发表时间: {dateFormat(data.createTime)}
                </div>
              </div>

              <div className="bottom-actions" style={{ padding: '5px 10px', display: 'flex', alignItems: 'center', zIndex: 10, background: '#fff', width: '100%', height: 40, position: 'fixed', left: 0, bottom: -1, borderTop: '1px solid #ddd', }}>
                <div className="input" onClick={()=>setVisiBle(true)} style={{ display: "flex", alignItems: "center", padding: '0 10px', width: 160, borderRadius: 20, height: 30, background: "#eee", fontSize: 16 }}>
                  <EditSOutline style={{fontSize:16, marginRight:5}}/>
                  <span>友善评论</span>
                </div>
                <div className="actions-list" style={{ display: "flex", alignItems: "center", padding: '0 10px', flex: 1, justifyContent: "space-around" }}>
                    <Badge content={data.commentNum} >
                        <MessageOutline style={{ fontSize: 22 }}  />
                    </Badge>

                    <Badge content={data.likeNum} >
                        <LikeOutline style={{ fontSize: 19 }} onClick={userInfo?run:AddLikeToNew}/>
                    </Badge>

                    <Badge content={data.readNum}>
                        <HeartOutline style={{ fontSize: 19 }} />
                    </Badge>

                    <SendOutline style={{ fontSize: 19 }} />
                </div>
              </div>

              <div className="clist">
                  {
                    commentList.length>0?
                    <div className='clist-box'>
                       <h2 style={{ paddingLeft: 15, fontSize: 16, fontWeight: 600 }}>评论 {data.commentNum}</h2>
                       {
                        commentList.map((item:any,index:any)=>{
                          return(
                            <div className="item-box" style={{ padding: 15 }} key={item.id}>
                              <div className="item-top"  style={{ display: 'flex', justifyContent: "space-between", alignItems: 'center' }}>
                                <div className="top-left" style={{ display: 'flex', justifyContent: "center", alignItems: 'center' }}>
                                  <Avatar src='' style={{ borderRadius: '50%', '--size': '30px' }}/>
                                  <span  style={{ fontSize: 18, marginLeft: 10, fontWeight: 600 }}>{item.userName}</span>
                                </div>
                                <div className="top-right" style={{ display: 'flex', justifyContent: "center", alignItems: 'center' }}>
                                    <Badge>
                                      <LikeOutline style={{ fontSize: 19 }} onClick={()=>AddLikeToNewComment(item,index)}/>
                                      <span>{item.likeNum?item.likeNum:"赞"}</span>
                                    </Badge>
                                </div>
                              </div>
                              <div className="item-content" style={{ marginTop: 10, paddingLeft: 40, fontSize: 16 }}>
                                  {item.content}
                              </div>
                                <div style={{ marginTop: 10, paddingLeft: 40, fontSize: 12, color: "#666" }}>
                                  <div className="time" style={{ marginTop: 15 }}>
                                    评论时间:{dateFormat(item.commentData)}
                                  </div>
                                </div>
                            </div>
                          )
                        })
                       }
                    </div>
                    :
                    <div>
                      <Empty description="暂无评论,请发布评论吧"/>
                    </div>
                  }
              </div>
          </div>


        <Popup
        visible={visible}

        bodyStyle={{
          borderTopLeftRadius: '8px',
          borderTopRightRadius: '8px',
          minHeight: '40vh',
        }}
        >
          <div className="pop-box" style={{padding:15}}>
            <div className="pop-top" style={{padding: '0 10px', height: 40, position: 'relative'}}>
              <h2 style={{ fontSize: 20, textAlign: 'center', color: '#333', height: 40, lineHeight: '40px' }}>欢迎评论</h2>
              <CloseOutline style={{ fontSize: 22, position: "absolute", right: 0, top: 10 }} 
                onClick={()=>setVisiBle(false)}
              />
            </div>
            <div className="content mt10">
              <TextArea
              placeholder='好话一句句, 让人心情变美丽'
              showCount
              maxLength={30}
              rows={5}
              style={{border:'1px solid #ddd',borderRadius:8,padding:10}}
              value={content}
              onChange={setContent}
              />
              <Button block onClick={todoAddComment} disabled={!content} className='mt20'>发布评论</Button>
            </div>
          </div>
        </Popup>
      </div>

  )
}

export default NewsDetail